package com.application.chiettinhdienluc.ui;

import java.io.File;
import java.util.Calendar;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.MainFragmentPagerAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.data.SharedPreferencesData;
import com.application.chiettinhdienluc.db.HinhAnhChiTietDataSource;
import com.application.chiettinhdienluc.dialog.ConfirmDialog;
import com.application.chiettinhdienluc.model.ChietTinhModel;
import com.application.chiettinhdienluc.model.HinhAnhChiTietModel;
import com.application.chiettinhdienluc.ui.ImageGridActivity.ImageGridFragment;
import com.application.chiettinhdienluc.utils.AlbumUtil;
import com.application.chiettinhdienluc.utils.Utils;

public class MainTabFragmentActivity extends SherlockFragmentActivity {

	public final String TAG = MainTabFragmentActivity.class.getSimpleName();
	
	private final int TAKE_A_PICTURE = 1002;
	
	private ViewPager  mViewPager;
	private ActionBar actionbar;
	private Resources res;
	public static final int MODE_DEFAULT = 0;
	public static final int MODE_EDITABLE = 1;
	public static final int MODE_NEW_INPUT = 2;
	public static final String STR_EXTRA_IMODE = "str_imode";
	private SimpleOnPageChangeListener pageChangeListener;
	private boolean exitAfterSave = false;

	private ProgressDialog progressDialog;


	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progressDialog = progressDialog;
	}

	public void setExitAfterSave(boolean exitAfterSave) {
		this.exitAfterSave = exitAfterSave;
	}

	public boolean isExitAfterSave() {
		return exitAfterSave;
	}

	private static int iMode = MODE_DEFAULT;

	public static int getiMode() {
		return MainTabFragmentActivity.iMode;
	}

	public static void setiMode(int iMode) {
		MainTabFragmentActivity.iMode = iMode;
	}

	private static MainTabFragmentActivity mainTabFragmentActivity = null;

	private ChietTinhModel localChietTinhMain = new ChietTinhModel();

	public ChietTinhModel getLocalChietTinhMain() {
		return localChietTinhMain;
	}

	public void setLocalChietTinhMain(ChietTinhModel localChietTinhMain) {
		this.localChietTinhMain = localChietTinhMain;
	}

	public static MainTabFragmentActivity getInstance() {
		return MainTabFragmentActivity.mainTabFragmentActivity;
	}

	public static void setMainTabActivity(MainTabFragmentActivity mainTabFragmentActivity) {
		MainTabFragmentActivity.mainTabFragmentActivity = mainTabFragmentActivity;
	}

	public void switchToKhachHangInfoTab()
	{		
		pageChangeListener.onPageSelected(TabItemEnum.USER.getIndexTab());
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_tabs_pager);
		res = getResources();

		MainTabFragmentActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		MainTabFragmentActivity.mainTabFragmentActivity = this;

		Intent intent = getIntent() != null ? getIntent() : null;

		if(intent != null && savedInstanceState == null)
		{
			Bundle bundle = intent.getExtras() != null ? intent.getExtras() : null;

			int iMode = bundle.containsKey(STR_EXTRA_IMODE) ? bundle.getInt(STR_EXTRA_IMODE) : MODE_DEFAULT;

			MainTabFragmentActivity.iMode = iMode;

			if(MainTabFragmentActivity.iMode == MODE_NEW_INPUT)
			{
				try
				{
					// get the current date
					final Calendar c = Calendar.getInstance();
					int mDay = c.get(Calendar.DAY_OF_MONTH);
					int mMonth = c.get(Calendar.MONTH) + 1;
					int mYear = c.get(Calendar.YEAR);	

					StringBuilder currentDate = new StringBuilder()								
					.append(mDay).append('/')
					.append(mMonth).append('/')
					.append(mYear);

					String name = MainApplication.getNguoiDung().get_MaNVien();
					
					if(!TextUtils.isEmpty(name))
					{
						GlobalData.globalChietTinh.set_NhanVienKhaoSat(name);
						GlobalData.globalChietTinh.set_ThucHien(name);
					}

					GlobalData.globalChietTinh.set_NgayND(currentDate.toString().trim());
					GlobalData.globalChietTinh.set_NgayKhaoSat(currentDate.toString().trim());
					GlobalData.globalChietTinh.set_NgayChietTinh(currentDate.toString().trim());

					String[] arrayTrangThaiHoSoId = res.getStringArray(R.array.array_trangthaihoso_id);
					GlobalData.globalChietTinh.set_TrangThai(arrayTrangThaiHoSoId.length > 0 ? arrayTrangThaiHoSoId[0] : "");
				}
				catch(Exception e){}

				Utils.showMess(getString(R.string.hint_editable_mode));
			}
			
			localChietTinhMain.cloneObject(GlobalData.globalChietTinh);

			if(MainApplication.getAppContext() != null)
			{
				Intent broadcastIntent = new Intent();
				broadcastIntent.setAction("com.application.chiettinhdienluc.ui.RefreshUserInfo");
				MainApplication.getAppContext().sendBroadcast(broadcastIntent);
			}
		}
		else
		{
			localChietTinhMain.cloneObject(GlobalData.globalChietTinh);
		}
		
		actionbar = getSupportActionBar();

		progressDialog = new ProgressDialog(this);	
		progressDialog.setMessage(res.getString(R.string.str_warning_saving_data));
		progressDialog.setCancelable(true);
		progressDialog.setCanceledOnTouchOutside(false);

		mViewPager = (ViewPager)findViewById(R.id.pager);
		FragmentManager fm = getSupportFragmentManager();

		/** Defining a listener for pageChange */
		pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
			@Override
			public void onPageSelected(final int position) {
				super.onPageSelected(position);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
					}
				});
				actionbar.setSelectedNavigationItem(position);
			}
		};

		/** Setting the pageChange listner to the viewPager */
		mViewPager.setOnPageChangeListener(pageChangeListener);

		/** Creating an instance of FragmentPagerAdapter */
		MainFragmentPagerAdapter fragmentPagerAdapter = new MainFragmentPagerAdapter(fm);

		mViewPager.setAdapter(fragmentPagerAdapter);
		
		mViewPager.setPageMarginDrawable(R.drawable.grey_background_pattern);
		mViewPager.setPageMargin(res.getDimensionPixelSize(R.dimen.page_margin_width));
		mViewPager.setOffscreenPageLimit(5);
		mViewPager.setDrawingCacheEnabled(true);
		mViewPager.setAlwaysDrawnWithCacheEnabled(true);
		mViewPager.setDrawingCacheQuality (ViewPager.DRAWING_CACHE_QUALITY_HIGH);

		/** Defining tab listener */
		ActionBar.TabListener tabListener = new ActionBar.TabListener() {
			@Override
			public void onTabSelected(final Tab tab, FragmentTransaction ft) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						invalidateOptionsMenu();
					}
				});
				mViewPager.setCurrentItem(tab.getPosition(), false);
				
			}

			@Override
			public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			}

			@Override
			public void onTabReselected(Tab tab, FragmentTransaction ft) {
			}
		};

		/** Creating Android Tab */
		// Tab tab = actionabar.newTab().setText("My Friends").setIcon(R.drawable.myfriends).setTabListener(tabListener);
		Tab tab = actionbar.newTab().setText(getString(R.string.tab_name_userinfo)).setTabListener(tabListener);
		
		actionbar.addTab(tab);
		tab = actionbar.newTab().setText(getString(R.string.tab_name_khaosatinfo)).setTabListener(tabListener);
		actionbar.addTab(tab);
		tab = actionbar.newTab().setText(getString(R.string.tab_name_vattuinfo)).setTabListener(tabListener);
		actionbar.addTab(tab);
		tab = actionbar.newTab().setText(getString(R.string.tab_name_nhanconginfo)).setTabListener(tabListener);
		actionbar.addTab(tab);
		tab = actionbar.newTab().setText(getString(R.string.tab_name_imginfo)).setTabListener(tabListener);
		actionbar.addTab(tab);
		tab = actionbar.newTab().setText(getString(R.string.tab_name_resultinfo)).setTabListener(tabListener);
		actionbar.addTab(tab);
		
		

		actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setDisplayShowHomeEnabled(true);
		//      actionabar.setDisplayShowTitleEnabled(false);
		//      actionabar.setDisplayShowHomeEnabled(false);
		//      iposItemTab = mViewPager.getCurrentItem();

		//      setupSlidingMenu();
		
		try 
		{
			if (savedInstanceState != null && savedInstanceState.containsKey("cameraImageUri")) {
				mPhotoCapturedUri = Uri.parse(savedInstanceState.getString("cameraImageUri"));
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}


	@Override
	protected void onResume() {
		super.onResume();
		MainTabFragmentActivity.mainTabFragmentActivity = this;
	}

	@Override
	protected void onDestroy() {
		MainTabFragmentActivity.mainTabFragmentActivity = null;
		super.onDestroy();
	}

	//  private int iposItemTab;

//	private final int OPTIONMENU_MENU_MAIN	               	= 0;
//	private final int OPTIONMENU_SUBMENU_CREATENEW          = OPTIONMENU_MENU_MAIN + 1;
//	private final int OPTIONMENU_SUBMENU_VIEWDETAILS     	= OPTIONMENU_SUBMENU_CREATENEW + 1;
//	private final int OPTIONMENU_SUBMENU_PRINT     			= OPTIONMENU_SUBMENU_VIEWDETAILS + 1;
//	private final int OPTIONMENU_SUBMENU_EXIT         		= OPTIONMENU_SUBMENU_PRINT + 1;
//
//	private final int OPTIONMENU_MENU_EDIT	               	= OPTIONMENU_SUBMENU_EXIT + 1;
//	private final int OPTIONMENU_MENU_SAVE	               	= OPTIONMENU_MENU_EDIT + 1;
//	private final int TOTAL_ITEM_MENU						= OPTIONMENU_MENU_SAVE + 1;


	private final int OPTIONMENU_MENU_SAVE	               	= 0;
	private final int OPTIONMENU_MENU_TAKE_PHOTO            = OPTIONMENU_MENU_SAVE + 1;
	
	private final short ORDER_POS_FIRST = 1;
	private final short ORDER_POS_SECOND = ORDER_POS_FIRST + 1;
	private final short ORDER_POS_THIRD = ORDER_POS_SECOND + 1;

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		if(res == null) return false;
		try {
			if(menu != null)
			{	
				menu.close();
				menu.clear();
			}

			if(mViewPager.getCurrentItem() != TabItemEnum.IMAGE.getIndexTab())
			{
				menu.add(OPTIONMENU_MENU_SAVE, OPTIONMENU_MENU_SAVE, ORDER_POS_FIRST/*Menu.NONE*/, R.string.str_resultinfo_btn_save)
				.setIcon(R.drawable.content_save)
				//          .setTitle(R.string.str_optionM_enableInEar)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);    // add to actionbar
			}
			else
			{
				menu.add(OPTIONMENU_MENU_TAKE_PHOTO, OPTIONMENU_MENU_TAKE_PHOTO, ORDER_POS_FIRST/*Menu.NONE*/, R.string.str_resultinfo_btn_take_photo)
				.setIcon(R.drawable.ic_camera_option_menu)
				//          .setTitle(R.string.str_optionM_enableInEar)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);    // add to actionbar
			}

			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public void onBackPressed() {
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
		MainApplication.getAppContext().sendBroadcast(broadcastIntent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId())
		{
		case android.R.id.home:
			Intent broadcastIntent = new Intent();
			broadcastIntent.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
			MainApplication.getAppContext().sendBroadcast(broadcastIntent);

			break;
		case OPTIONMENU_MENU_SAVE:
			Log.v("HAI", "OPTIONMENU_MENU_SAVE");
			if(MainApplication.getAppContext() != null)
			{
				if(!TextUtils.isEmpty(SharedPreferencesData.getMaDonViQuanLy(MainApplication.getAppContext()))
						|| !TextUtils.isEmpty(MainApplication.getMaKhuVuc()))
				{
					Fragment fragmentUser = findFragment(TabItemEnum.USER.getIndexTab());
					if(fragmentUser != null && fragmentUser instanceof KhachHangInfoFragment)
					{
						String dpn = ((KhachHangInfoFragment)fragmentUser).getEdt_dpn().getText().toString();
						String address = ((KhachHangInfoFragment)fragmentUser).getEdt_address().getText().toString();

						if(TextUtils.isEmpty(dpn) || TextUtils.isEmpty(address)){
							showDialogWarningInputKHInfo();
						}
						else
						{
							showHideProgressDialog(true);

							Intent broadcastIntent2 = new Intent();
							broadcastIntent2.setAction("com.application.chiettinhdienluc.ui.SaveResultInfo");
							MainApplication.getAppContext().sendBroadcast(broadcastIntent2);
							Log.i(TAG, "Save chiet tinh");
						}
					}
				}	
				else
				{
					Utils.showMess(res.getString(R.string.str_warning_missing_pb_id));
				}
			}
			return true;
		case OPTIONMENU_MENU_TAKE_PHOTO:
			takePhoto();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void showDialogWarningInputKHInfo() {
		Dialog dialog = null;
		ConfirmDialog.ConfirmBuilder customBuilder = new ConfirmDialog.ConfirmBuilder(this);
		String msg = res.getString(R.string.str_warning_must_input_dpn_or_address);

		customBuilder.setTitle(res.getString(R.string.str_thongBao))
		.setMessage(msg)
		//		.setNegativeButton(res.getString(R.string.str_no), new DialogInterface.OnClickListener() {
		//			public void onClick(DialogInterface dialog, int which) {
		//				if(dialog != null)
		//					dialog.dismiss();
		//				if(MainTabFragmentActivity.getInstance() != null)
		//				{
		//					MainTabFragmentActivity.getInstance().finish();
		//				}					
		//			}
		//		})
		.setPositiveButton(res.getString(R.string.str_btn_ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(dialog != null) dialog.dismiss();
				switchToKhachHangInfoTab();
			}
		});
		dialog = customBuilder.create();

		if(dialog != null) dialog.show();
	}



	public enum TabItemEnum {
		USER(0), KHAOSAT(1), VATTU(2), NHANCONG(3), IMAGE(4), RESULT(5);

		int indexItem = 0;

		TabItemEnum(int index) {
			this.indexItem = index;
		}

		final int getIndexTab()
		{
			return indexItem;
		}
	}

	private Fragment findFragment(int position)
	{
		return getSupportFragmentManager() != null ? getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.pager+":" + position) : null;
	}

	public void saveFunction()
	{
		if(MainApplication.getAppContext() != null)
		{
			if(!TextUtils.isEmpty(SharedPreferencesData.getMaDonViQuanLy(MainApplication.getAppContext()))
					|| !TextUtils.isEmpty(MainApplication.getMaKhuVuc()))
			{
				Fragment fragmentUser = findFragment(TabItemEnum.USER.getIndexTab());
				if(fragmentUser != null && fragmentUser instanceof KhachHangInfoFragment)
				{
					String dpn = ((KhachHangInfoFragment)fragmentUser).getEdt_dpn().getText().toString();
					String address = ((KhachHangInfoFragment)fragmentUser).getEdt_address().getText().toString();

					if(TextUtils.isEmpty(dpn) || TextUtils.isEmpty(address)){
						showDialogWarningInputKHInfo();
					}
					else
					{
						showHideProgressDialog(true);
						exitAfterSave = true;
						Intent broadcastIntent2 = new Intent();
						broadcastIntent2.setAction("com.application.chiettinhdienluc.ui.SaveResultInfo");
						MainApplication.getAppContext().sendBroadcast(broadcastIntent2);
						Log.i(TAG, "Save chiet tinh");
					}
				}
			}	
			else
			{
				Utils.showMess(res.getString(R.string.str_warning_missing_pb_id));
			}
		}
	}

	public void showHideProgressDialog(boolean show)
	{
		if(show)
		{
			if(progressDialog != null && !progressDialog.isShowing() && !MainTabFragmentActivity.this.isFinishing())
				progressDialog.show();
		}
		else
		{
			if(progressDialog != null && progressDialog.isShowing() && !MainTabFragmentActivity.this.isFinishing())
				progressDialog.dismiss();
		}
	}

	public void finishActivityResult()
	{
		Intent intent = getIntent();			
		setResult(RESULT_OK, intent);
		this.finish();
	}
	
	private Uri mPhotoCapturedUri;
	public void takePhoto()
	{		
		try {
			if(Utils.sdCardMounted())
			{			
				mPhotoCapturedUri = Uri.fromFile(AlbumUtil.getInstance().setUpPhotoFile());
				Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoCapturedUri);
				startActivityForResult(cameraIntent, TAKE_A_PICTURE);		 
			}
		} catch (Exception e) {

			e.printStackTrace();
		}		
	}

	@Override
	public void onSaveInstanceState(Bundle outState) 
	{
		super.onSaveInstanceState(outState);

		try 
		{
			if (mPhotoCapturedUri != null) 
			{
				outState.putString("cameraImageUri", mPhotoCapturedUri.toString());
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if (requestCode == TAKE_A_PICTURE) {
				if (resultCode == RESULT_OK) {
					
					
					try {
						if (mPhotoCapturedUri != null) {
							// get the current date
							final Calendar c = Calendar.getInstance();
							int mDay = c.get(Calendar.DAY_OF_MONTH);
							int mMonth = c.get(Calendar.MONTH) + 1;
							int mYear = c.get(Calendar.YEAR);
							
							String imagePath = Utils.getMediaPath(MainTabFragmentActivity.this, mPhotoCapturedUri);
							String[] splitTexts = imagePath.split("/");
							
							//don't need to save now, wait till the save broadcast happen
													
							StringBuilder ngayChup = new StringBuilder()								
							.append(mDay).append('/')
							// Month is 0 based so add 1
							.append(mMonth).append('/')
							.append(mYear);
							
							HinhAnhChiTietModel ha = new HinhAnhChiTietModel();
							
							ha.setSubmitted(0);
							ha.setFilename(splitTexts[splitTexts.length - 1]);
							ha.setNgaychup(ngayChup.toString());
												
							
							if(GlobalData.globalChietTinh != null && GlobalData.globalChietTinh.get_Id() > 0)
							{	
								HinhAnhChiTietDataSource dbHelper = new HinhAnhChiTietDataSource();
								ha.setHosochiettinhid(""+GlobalData.globalChietTinh.get_Id());
								
								long pos = dbHelper.addNewImageInfo(ha);
								
								if(pos > 0) 									
									Utils.showMess(getString(R.string.str_hint_msg_save_img_success));
								
							}
							else {
								ha.setHosochiettinhid("");
							}							
							
							GlobalData.HinhAnhList.add(ha);
							
							Fragment fragmentImage = findFragment(TabItemEnum.IMAGE.getIndexTab());
							
							if(fragmentImage != null && fragmentImage instanceof ImageGridFragment)
							{
								((ImageGridFragment)fragmentImage).refreshImageGridView();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else //delete tmp file if cancel take picture
				{
					if (mPhotoCapturedUri != null) {
						String imagePath = Utils.getMediaPath(MainTabFragmentActivity.this, mPhotoCapturedUri);
						
						File tmpFile = new File(imagePath);
						
						if(tmpFile != null && tmpFile.exists() && tmpFile.isFile())
						{
							tmpFile.delete();
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
